package com.gimi.cloud.jimi.manage.service.prod.impl;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.MyBeanUtils;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.commonService.common.JmOperationLogService;
import com.gimi.cloud.jimi.dao.dao.prod.CategoryBrandRelaDao;
import com.gimi.cloud.jimi.dao.dao.prod.ProdBrandDao;
import com.gimi.cloud.jimi.dao.dao.prod.ProdCategoryDao;
import com.gimi.cloud.jimi.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.jimi.dto.base.BaseDTO;
import com.gimi.cloud.jimi.dto.prod.EcProdCatModelValueDTO;
import com.gimi.cloud.jimi.dto.prod.ProdBrandDTO;
import com.gimi.cloud.jimi.dto.prod.ProdCatModelDTO;
import com.gimi.cloud.jimi.dto.prod.ProdCategoryDTO;
import com.gimi.cloud.jimi.entity.prod.CategoryBrandRelaEntity;
import com.gimi.cloud.jimi.entity.prod.ProdBrandEntity;
import com.gimi.cloud.jimi.entity.prod.ProdCategoryEntity;
import com.gimi.cloud.jimi.manage.service.prod.CategoryService;
import com.gimi.cloud.jimi.manage.service.prod.ProdCatModelService;
import com.gimi.cloud.jimi.manage.service.prod.ProdCatModelValueService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    private final ProdCategoryDao categoryDao;
    private final CategoryBrandRelaDao categoryBrandRelaDao;
    private final JmOperationLogService jmOperationLogService;
    private final ProdCatModelService prodCatModelService;
    private final ProdCatModelValueService prodCatModelValueService;
    private final ProdBrandDao prodBrandDao;
    private static final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    public CategoryServiceImpl(ProdCategoryDao categoryDao, CategoryBrandRelaDao categoryBrandRelaDao, ProdCatModelValueService prodCatModelValueService,
                               ProdCatModelService prodCatModelService, JmOperationLogService jmOperationLogService, ProdBrandDao prodBrandDao) {
        this.categoryDao = categoryDao;
        this.jmOperationLogService = jmOperationLogService;
        this.categoryBrandRelaDao = categoryBrandRelaDao;
        this.prodCatModelValueService = prodCatModelValueService;
        this.prodCatModelService = prodCatModelService;
        this.prodBrandDao = prodBrandDao;
    }


//    /**
//     * 添加商品品类
//     *
//     * @param prodCategoryDTO
//     * @return
//     */
//    @Override
//    @Transient
//    public ResponseCodeEnum categoryAdd(ProdCategoryDTO prodCategoryDTO) {
//
//        //判断是否已经存在该名称的商品
//        List<ProdCategoryDTO> isExist = categoryDao.getCategoryListByNameForAdd(prodCategoryDTO.getProdCatName(), prodCategoryDTO.getCatGrade());
//        if (isExist != null && isExist.size() > 0) {
//            return ResponseCodeEnum.PRODCATNAME_IS_EXIT;
//        }
//
//        prodCategoryDTO.setImgUrl(AliOSSUtil.getFilePath(prodCategoryDTO.getImgUrl()));
//        ProdCategoryEntity categoryEntity = new ProdCategoryEntity();
//        BeanUtils.copyProperties(prodCategoryDTO, categoryEntity);
//        categoryDao.insertSelective(categoryEntity);
//
//        //如果是添加三级品类，那么需要添加品牌和品类的中间表
//        CategoryBrandRelaEntity categoryBrandRelaEntity = null;
//        if (3 == prodCategoryDTO.getCatGrade()) {
//            categoryBrandRelaEntity = new CategoryBrandRelaEntity();
//            categoryBrandRelaEntity.setProdBrandId(prodCategoryDTO.getPdId() + "");
//            categoryBrandRelaEntity.setProdCatId(prodCategoryDTO.getProdCatId());
//            categoryBrandRelaDao.insert(categoryBrandRelaEntity);
//        }
//
//        //添加操作日志
//        BaseDTO baseDTO = new BaseDTO();
//        BeanUtils.copyProperties(prodCategoryDTO, baseDTO);
//        jmOperationLogService.insertAddLog(baseDTO, prodCategoryDTO.getProdCatId() + "", "categoryAdd", "ec_prod_category", "添加商品品类");
//        return ResponseCodeEnum.SUCCESSED;
//    }

//    /**
//     * 更新商品品类
//     *
//     * @param prodCategoryDTO
//     * @return
//     */
//    @Override
//    @Transient
//    public ResponseCodeEnum categoryUpdate(ProdCategoryDTO prodCategoryDTO) {
//        //判断分类级别和父类id是否改变
//        ProdCategoryDTO entity = categoryDao.findProdCategoryByProdCatId(prodCategoryDTO);
//        if (entity.getCatGrade() != prodCategoryDTO.getCatGrade() || !entity.getParentCatId().equals(prodCategoryDTO.getParentCatId())) {
//            return ResponseCodeEnum.PRODCAT_CANNOT_CHANGE;
//        }
//        //判断当前品类级别里是否有重名
//        List<ProdCategoryDTO> isExist = categoryDao.getCategoryListByName(prodCategoryDTO.getProdCatName(), prodCategoryDTO.getCatGrade(), prodCategoryDTO.getProdCatId());
//        if (isExist != null && isExist.size() > 0) {
//            return ResponseCodeEnum.PRODCATNAME_UPDATE_IS_EXIT;
//        }
//
//        prodCategoryDTO.setImgUrl(AliOSSUtil.getFilePath(prodCategoryDTO.getImgUrl()));
//        ProdCategoryEntity categoryEntity = new ProdCategoryEntity();
//        BeanUtils.copyProperties(prodCategoryDTO, categoryEntity);
//        ProdCategoryEntity categoryEntityTemp = categoryDao.selectByPrimaryKey(prodCategoryDTO.getProdCatId());
//        //将原来的禁用或启用，重新赋值给对象
//        categoryEntity.setIsDelete(categoryEntityTemp.getIsDelete());
//        categoryEntity.setVersion(categoryEntityTemp.getVersion());
//        categoryDao.updateByPrimaryKey(categoryEntity);
//
//        //如果是修改三级品类，那么需要修改品牌和品类的中间表
//        CategoryBrandRelaEntity categoryBrandRelaEntity = null;
//        if (3 == prodCategoryDTO.getCatGrade()) {
//            categoryBrandRelaEntity = categoryBrandRelaDao.findByProdCatId(prodCategoryDTO.getProdCatId());
//            categoryBrandRelaEntity.setProdBrandId(prodCategoryDTO.getPdId() + "");
//            categoryBrandRelaDao.updateByPrimaryKey(categoryBrandRelaEntity);
//        }
//        //添加操作日志
//        BaseDTO baseDTO = new BaseDTO();
//        BeanUtils.copyProperties(prodCategoryDTO, baseDTO);
//        jmOperationLogService.insertUpdateLog(baseDTO, "categoryUpdate", "ec_prod_category", prodCategoryDTO.getProdCatId() + "", "更新商品品类");
//
//        return ResponseCodeEnum.SUCCESSED;
//    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public ProdCategoryDTO saveOrUpdate(ProdCategoryDTO dto) {
        ProdCategoryEntity prodCategoryEntity = null;
        if (StringUtils.isNotBlank(dto.getProdCatId())) {
            prodCategoryEntity = categoryDao.queryBy("prod_cat_id", dto.getProdCatId());
            if (null == prodCategoryEntity) {
                throw new MsgException(ResponseCodeEnum.FAILURE, "未获取到id为" + dto.getProdCatId() + "的品类，保存失败");
            }
            //判断品类分类级别是否改变
            if (prodCategoryEntity.getCatGrade() != dto.getCatGrade()) {
                throw new MsgException(ResponseCodeEnum.PRODCAT_CANNOT_CHANGE, "商品品类分类级别和父类编号不能改变");
            }
            //判断当前品类级别里是否有重名
            List<ProdCategoryDTO> isExist = categoryDao.getCategoryListByNameNew(dto.getProdCatName(), dto.getCatGrade(), dto.getProdCatId());
            if (isExist != null && isExist.size() > 0) {
                throw new MsgException(ResponseCodeEnum.PRODCATNAME_IS_EXIT, "商品品类名称已经存在,更新失败");
            }
        } else {
            prodCategoryEntity = new ProdCategoryEntity();
            //判断是否已经存在该名称的商品
            List<ProdCategoryDTO> isExist = categoryDao.getCategoryListByNameForAddNew(dto.getProdCatName(), dto.getCatGrade());
            if (isExist != null && isExist.size() > 0) {
                throw new MsgException(ResponseCodeEnum.PRODCATNAME_IS_EXIT, "商品品类名称已经存在,添加失败");
            }
        }
        //长路径改成短路径
        dto.setImgUrl(AliOSSUtil.getFilePath(dto.getImgUrl()));
        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(dto, prodCategoryEntity);
        //false代表修改，true代表新增
        boolean flag = false;
        if (StringUtil.isNotBlank(prodCategoryEntity.getProdCatId())) {
            categoryDao.baseUpdateByPrimaryKey(prodCategoryEntity);
        } else {
            //自动生成主键
            prodCategoryEntity.setProdCatId(this.createCurrentCategoryId(dto));
            categoryDao.insertSelective(prodCategoryEntity);
            flag = true;
        }

        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(prodCategoryEntity, dto);
        //第三级,生成模版属性及模版值
        if (dto.getCatGrade() == 3) {
            //模版属性id
            List<Long> prodCatModelId = new ArrayList<>();
            //模版属性值id
            List<Long> prodCatModelValueId = new ArrayList<>();
            if (null != dto.getProdCatModel() && dto.getProdCatModel().size() > 0) {
                for (ProdCatModelDTO catmodel : dto.getProdCatModel()) {
                    //如果模版属性名不为空
                    if (StringUtil.isNotBlank(catmodel.getProdPropName())) {
                        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(dto, catmodel);
                        //设置关联id
                        catmodel.setProdCatId(prodCategoryEntity.getProdCatId());
                        catmodel = prodCatModelService.saveOrUpdate(catmodel);
                        prodCatModelId.add(catmodel.getModelId());
                        //如果模版值不为空
                        if (null != catmodel.getProdCatModelValue() && catmodel.getProdCatModelValue().size() > 0) {
                            for (EcProdCatModelValueDTO catModelValue : catmodel.getProdCatModelValue()) {
                                if (StringUtil.isNotBlank(catModelValue.getModelValue())) {
                                    MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(dto, catModelValue);
                                    catModelValue.setModelId(catmodel.getModelId());
                                    prodCatModelValueService.saveOrUpdate(catModelValue);
                                    prodCatModelValueId.add(catModelValue.getCmId());
                                }
                            }
                        }
                    }
                }
            }
            //删除失效的品类模版值
            prodCatModelValueService.deleteCatModelValueByCatIdExcludeCmIds(dto, prodCategoryEntity.getProdCatId(), prodCatModelValueId);
            //删除失效的品类模版
            prodCatModelService.deleteProdCatModelByCatIdExcludeModelIds(dto, prodCategoryEntity.getProdCatId(), prodCatModelId);
            CategoryBrandRelaEntity categoryBrandRelaEntity = null;
            //添加品牌
            if (flag) {
                categoryBrandRelaEntity = new CategoryBrandRelaEntity();
                categoryBrandRelaEntity.setProdBrandId(dto.getPdId() + "");
                categoryBrandRelaEntity.setProdCatId(dto.getProdCatId());
                categoryBrandRelaDao.insert(categoryBrandRelaEntity);
            } else {
                categoryBrandRelaEntity = categoryBrandRelaDao.findByProdCatId(dto.getProdCatId());
                categoryBrandRelaEntity.setProdBrandId(dto.getPdId() + "");
                categoryBrandRelaDao.updateByPrimaryKey(categoryBrandRelaEntity);
            }

        }
        //添加操作日志
        if (flag) {
            jmOperationLogService.insertAddLog(dto, dto.getProdCatId() + "", "saveOrUpdate",
                    "ec_prod_category", "添加商品品类");
        } else {
            jmOperationLogService.insertUpdateLog(dto, "saveOrUpdate", "ec_prod_category",
                    dto.getProdCatId() + "", "更新商品品类");
        }
        return dto;
    }

    /**
     * 生成品类id的策略
     *
     * @param dto
     * @return
     */
    public String createCurrentCategoryId(ProdCategoryDTO dto) {
        //因业务变更，id不允许前端填写，由后台生成
        //先查出库里最大值，然后加1即可.
        //截取的开始长度分别为：1级1，2级3，3级6
        //拼接0的位数
        int length = 0;
        //截取的开始长度
        int subStart = 0;
        if (dto.getCatGrade() == 1) {
            length = 2;
            subStart = 1;
        } else if (dto.getCatGrade() == 2) {
            length = 3;
            subStart = 3;
        } else {
            length = 4;
            subStart = 6;
        }
        String maxValue = this.findMaxCatIdByGrade(dto.getParentCatId(), subStart);
        String newStr = "0";
        if (!"0".equals(maxValue)) {
            newStr = maxValue.replaceFirst("^0*", "");
        }
        int maxV = new Integer(newStr) + 1;
        //新增方法，为不同的级别拼接上相应的0的个数
        String id = String.format("%0" + length + "d", maxV);
        //再将父级id拼接上(1级时不拼，其他拼接)
        if (dto.getCatGrade() > 1) {
            id = dto.getParentCatId() + id;
        }
        return id;
    }


    /**
     * 通过主键id删除商品品类
     *
     * @param prodCategoryDTO
     * @return
     */
    @Override
    public Boolean categoryDelete(ProdCategoryDTO prodCategoryDTO) {
        categoryDao.deleteCategory(prodCategoryDTO);
        //添加操作日志
        BaseDTO baseDTO = new BaseDTO();
        BeanUtils.copyProperties(prodCategoryDTO, baseDTO);
        jmOperationLogService.insertUpdateLog(baseDTO, "categoryDelete", "ec_prod_category", prodCategoryDTO.getProdCatId() + "", "通过主键id删除商品品类，逻辑删除/启用");
        return true;
    }

    @Override
    public List<ProdCategoryDTO> getCategoryListById(ProdCategoryDTO prodCategoryDTO) {
        List<ProdCategoryDTO> result = categoryDao.getCategoryListById(prodCategoryDTO.getProdCatId());
        if (result != null) {
            for (ProdCategoryDTO pc : result) {
                pc.setImgUrl(AliOSSUtil.getFileUrl(pc.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
            }
        }
        return result;
    }

    @Override
    public List<ProdCategoryDTO> getCategoryList() {
        List<ProdCategoryDTO> result = categoryDao.getCategoryList();
        if (result != null) {
            for (ProdCategoryDTO pc : result) {
                pc.setImgUrl(AliOSSUtil.getFileUrl(pc.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
            }
        }
        return result;
    }

    @Override
    public Page<ProdCategoryDTO> getCategoryPageList(ProdCategoryDTO prodCategoryDTO) {
        PageHelper.startPage(prodCategoryDTO.getCurrentPage(), prodCategoryDTO.getPageSize());
        List<ProdCategoryDTO> result = categoryDao.queryPageList(prodCategoryDTO);
        if (result != null) {
            for (ProdCategoryDTO pc : result) {
                pc.setImgUrl(AliOSSUtil.getFileUrl(pc.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
            }
        }
        Page<ProdCategoryDTO> page = new Page(new PageInfo<>(result));
        return page;
    }

//    @Override
//    public ProdCategoryDTO gotoEditProdCategory(ProdCategoryDTO prodCategoryDTO) {
//        ProdCategoryDTO newprodCategoryDTO = categoryDao.findProdCategoryByProdCatId(prodCategoryDTO);
//        newprodCategoryDTO.setImgUrl(AliOSSUtil.getFileUrl(newprodCategoryDTO.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
//
//        //添加操作日志
//        jmOperationLogService.insertQueryLog(new BaseDTO(), "gotoEditProdCategory", "ec_prod_category",
//                prodCategoryDTO.getProdCatId() + "", "转跳到编辑界面");
//        return newprodCategoryDTO;
//    }

    @Override
    public ProdCategoryDTO loadPordCategoryAndInitModelInfo(ProdCategoryDTO dto, String prodCatId) {
        ProdCategoryDTO ecPordCategory = this.load(dto, prodCatId);
        if (null == ecPordCategory) {
            return null;
        }
        ProdCatModelDTO prodCatModelDTO = new ProdCatModelDTO();
        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(dto, prodCatModelDTO);
        //封装品类模板和品类模板属性值
        ecPordCategory.setProdCatModel(prodCatModelService.getProdCatModelByCatId(prodCatModelDTO, prodCatId));
        //封装品牌
        CategoryBrandRelaEntity categoryBrandRelaEntity = null;
        if (3 == ecPordCategory.getCatGrade()) {
            categoryBrandRelaEntity = categoryBrandRelaDao.findByProdCatId(ecPordCategory.getProdCatId());
            ProdBrandEntity prodBrandEntity = prodBrandDao.findByProdProdBrandId(StringUtil.toInt(categoryBrandRelaEntity.getProdBrandId()));
            if (prodBrandEntity != null) {
                ecPordCategory.setProdBrandName(prodBrandEntity.getProdBrandName());
                ecPordCategory.setPdId(prodBrandEntity.getPdId().intValue());
            }
        }
        //短路径改长路径
        ecPordCategory.setImgUrl(AliOSSUtil.getFileUrl(ecPordCategory.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
        return ecPordCategory;
    }

    @Override
    public List<ProdCatModelDTO> getThreeProdCatModel(ProdCatModelDTO dto) {
        ProdBrandDTO prodBrandDTO = prodBrandDao.selectProdBrandByProdCatId(dto);
        //通过三级品类id查询模板及其属性
        List<ProdCatModelDTO> list = prodCatModelService.queryList(dto, true);
        for (ProdCatModelDTO ecProdCatModelDTO : list) {
            ecProdCatModelDTO.setProdBrandName(prodBrandDTO.getProdBrandName());
        }
        return list;
    }

    @Override
    public ProdCategoryDTO load(ProdCategoryDTO dto, Object id) {
        ProdCategoryEntity prodCategoryEntity = categoryDao.selectByPrimaryKey( id);
        if (null == prodCategoryEntity) {
            return null;
        }
        ProdCategoryDTO prodCategoryDTO = new ProdCategoryDTO();
        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(prodCategoryEntity, prodCategoryDTO);
        //封装父类品类名称
        ProdCategoryEntity parentProdCategoryEntity = null;
        //如果父类是根级别，那么将父类id设为空串
        if ("0".equals(prodCategoryEntity.getParentCatId())) {
            prodCategoryDTO.setParentCatName("");
        } else {
            parentProdCategoryEntity = categoryDao.selectByPrimaryKey(prodCategoryEntity.getParentCatId());
            prodCategoryDTO.setParentCatName(parentProdCategoryEntity.getProdCatName());
        }
        return prodCategoryDTO;
    }

    @Override
    public List<ProdCategoryDTO> searchCategoryListByGrade(int i) {
        List<ProdCategoryDTO> result = categoryDao.searchCategoryListByGrade(i);
        if (result != null) {
            for (ProdCategoryDTO pc : result) {
                pc.setImgUrl(AliOSSUtil.getFileUrl(pc.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
            }
        }
        return result;
    }

    @Override
    public String findMaxCatIdByGrade(String parentCatId, int subStart) {
        QueryParam param = new QueryParam();
        String sql = "select ifnull(max(SUBSTRING(prod_cat_id," + subStart + ")),'0') from ec_prod_category where parent_cat_id = '" + parentCatId + "' ";
        param.setSql(sql);
        return categoryDao.findMaxCatIdByGrade(param);
    }

    @Override
    public List<Map<String, Object>> getCategoryListTree(ProdCategoryDTO prodCategoryDTO) {
        //查询品类表所有的数据
        List<ProdCategoryDTO> allcats = categoryDao.getAllProdCategory();
        if (allcats != null) {
            for (ProdCategoryDTO pc : allcats) {
                pc.setImgUrl(AliOSSUtil.getFileUrl(pc.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
            }
        }
        //将属于当前店铺的品类递归成树
        return toTree(allcats, 1, null);
    }

    @Override
    public List<ProdCategoryDTO> getCategoryListByParent(ProdCategoryDTO dto) {
        List<ProdCategoryDTO> result = null;
        List<ProdCategoryDTO> data = categoryDao.getCategoryListByParent(dto.getProdCatId());
        if (data != null && data.size() > 0) {
            result = data;
        } else {
            logger.info(String.format("===>找不到catId为%s的子品类", dto.getProdCatId()));
        }
        return result;
    }

    public List<Map<String, Object>> toTree(List<ProdCategoryDTO> prodCatDto, Integer servicePid, String parentId) {
        List<Map<String, Object>> results = new ArrayList<>();
        List<ProdCategoryDTO> temp = new ArrayList<>();
        if (servicePid == 1) {
            for (ProdCategoryDTO list : prodCatDto) {
                if (list.getCatGrade() != null && servicePid == list.getCatGrade()) {
                    temp.add(list);
                }
            }
        } else {
            for (ProdCategoryDTO list : prodCatDto) {
                if (list.getCatGrade() != null
                        && servicePid == list.getCatGrade()
                        && parentId.equals(list.getParentCatId())) {
                    temp.add(list);
                }
            }
        }
        if (temp.size() > 0) {
            for (ProdCategoryDTO cateDto : temp) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", cateDto.getProdCatId());
                map.put("name", cateDto.getProdCatName());
                List<Map<String, Object>> children
                        = toTree(prodCatDto, cateDto.getCatGrade() + 1, cateDto.getProdCatId());
                if (children.size() > 0) {
                    map.put("children", children);
                }
                results.add(map);
            }
        }
        return results;
    }
}
